package com.ljs.liojbackendjudgeservice.judge.codesandbox.imp;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ljs.libackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.ljs.libackendmodel.model.codesandbox.ExecuteCodeResponse;
import com.ljs.liojbackendcommon.common.ErrorCode;
import com.ljs.liojbackendcommon.exception.BusinessException;
import com.ljs.liojbackendjudgeservice.judge.codesandbox.CodeSandbox;


/**
 * 远程代码沙箱（实际调用接口的沙箱 ）
 */
public class RemoteCodeSandbox implements CodeSandbox {
    //保持安全性，定义请求头和密钥
    private static final String AUTH_REQUEST_HEADER="auth";
    private static final String AUTH_REQUEST_SECRET= "secretKey";


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        System.out.println("远程代码沙箱");
        String url="http://localhost:8080/executeCode";
        String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET.toString())
                .body(jsonStr)
                .execute()
                .body();
        if (responseStr==null){
            throw  new BusinessException(ErrorCode.API_REQUEST_ERROR,"executorCode remoteSandbox error"+responseStr);
        }
        return  JSONUtil.toBean(responseStr,ExecuteCodeResponse.class);
    }
}
